package main

import (
	"github.com/playnb/mustang/log"
	_ "io/ioutil"
	"net/http"
	"os"
	"strings"
)

func handleUpload(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
	var uploadBasePath = getCurrentDirectory() + "/htdoc"
	r.ParseForm()
	if r.Method == "POST" {
		value :=r.Form.Get("text");
		log.Debug("Upload Data :  %s ", value)
		result := ([]byte)(value);
		//result, err := ioutil.ReadAll(r.Body)
		//r.Body.Close()
		
		ss := strings.Split(r.RequestURI, "/")
		if len(ss) > 3 {
			fileName := strings.Join(ss[3:], "/")
			fileName = uploadBasePath + "/" + fileName
			fp, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0666)
			if err != nil {
				log.Error(err.Error())
			} else {
				_, err = fp.Write(result)
				if err != nil {
					log.Error(err.Error())
				} else {
					log.Trace("Upload File :%s OK!  data: %s", fileName, result)
				}
			}
		} else {
			log.Trace("Upload File :参数错误")
		}
	} else {
		log.Trace("Upload File :只接受POST请求")
	}
}
